package fr.unice.platdujour.chord;

import java.rmi.RemoteException;

public class ThreadHeartbeat extends Thread{
	
	/** Number of milliseconds between each heartbeat */
	private static final int DELAY_HEARTBEAT = 1000;
	
	/** The tracker containing the peers */
	private Tracker tracker;
	
	public ThreadHeartbeat(Tracker tracker){
		this.tracker = tracker;
	}
	
	/**
	 * Start the heartbeat (thread)
	 */
	public void run() {
		try {
			heartbeat(this.tracker.getRandomPeer(), DELAY_HEARTBEAT);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			this.run();
		}
	}
	
	/**
	 * The thread that check every DELAY_HEARTBEAT if the successor of the current peer
	 * is alive
	 * @param peer the current peer
	 * @param milliseconds the delay between each check
	 * @throws RemoteException
	 */
	public void heartbeat(Peer peer, int milliseconds) throws RemoteException {
		// TODO Auto-generated method stub
		while(true){
			System.out.println("Peer " + peer.getId() + "is alive.");
			try {
				Thread.sleep(milliseconds);
				heartbeat(peer.getSuccessor(), milliseconds);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
		}
	}
}
